package net.sh.dpinfrastructure.util;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;

import net.sh.dpinfrastructure.exception.DPException;


/**
 * 
 * 验证码生成工具类
 * 
 * @version 1.0
 * @since JDK1.7
 * @author shaohui
 * @company 上海朝阳永续信息技术有限公司
 * @copyright (c) 2015 SunTime Co'Ltd Inc. All rights reserved.
 * @date 2015年9月22日 下午3:13:34
 */
public final class DPCaptchaUtils {
    
    private static final int HEIGHT = 30;
    
    private static final int WIDTH = 100;
    
    private DPCaptchaUtils() {}
    
    /**
     * 
     * 获取验证码 （base64编码格式）
     *
     * @param captcha
     * @return
     * 
     * @author shaohui
     * @date 2015年9月22日 下午3:54:19
     */
    public static String getCaptchaImg(String captcha) {
        if (StringUtils.isBlank(captcha)) {
            throw new NullPointerException();
        }
        
        int captchaLength = captcha.length();
        
        int fontWidth = (WIDTH - 2) / captchaLength;
        int fontHeight = HEIGHT - 2;
        
        // 在内存中创建图象
        BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);  
        
        // 获取图形上下文
        Graphics2D g = image.createGraphics();
        
        // 设定背景色
        g.setBackground(Color.WHITE);
        
        //填充
        g.fillRect(0, 0, WIDTH, HEIGHT);
        
        //设定字体
        g.setFont(new Font("Times New Roman", Font.PLAIN + Font.BOLD + Font.ITALIC, fontHeight));
        
        // 画边框
        g.setColor(new Color(55, 55, 12));
        g.drawRect(0, 0, WIDTH - 1, HEIGHT - 1);
        
        // 随机产生100条干扰线，使图象中的认证码不易被其它程序探测到
        Random random = new Random();
        for (int i = 0; i < 100; i++) {
            g.setColor(new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256)));
            int x = random.nextInt(100);
            int y = random.nextInt(30);
            int xl = random.nextInt(12);
            int yl = random.nextInt(12);
            g.drawLine(x, y, x + xl, y + yl);
        }
        
        // 绘制验证码
        for (int i = 0; i < captchaLength; i++) {
            g.setColor(new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256)));
            g.drawString(String.valueOf(captcha.charAt(i)), i * fontWidth, HEIGHT - 2);
        }
        
        g.dispose();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] resultBuf = null;
        try {
            ImageIO.write(image, "gif", baos);
            resultBuf = baos.toByteArray();
        } catch (IOException e) {
            throw new DPException("生成验证码失败");
        }
        return new String(Base64.encodeBase64(resultBuf));
    }
    
}
